<template>
    <div>
        <div class="layout-route" v-show="!editData.visible">
            <div class="card card-search">
                <el-form :model="queryParams" ref="queryForm" v-show="showSearch" inline label-width="100px">
                    <el-form-item label="商品sku" prop="seller_sku">
                        <el-input v-model.trim="queryParams.seller_sku" placeholder="请输入商品sku" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                    <el-form-item label="供应商" prop="supply_id">
                        <SelectPage
                            v-model="queryParams.supply_id"
                            placeholder="请选择供应商"
                            :url="$api.supply.getSupplyList"
                            show_field="supply_name"
                            query_field="supply_name"
                            query_field2="spu"
                            filterable
                            clearable
                            popper-class="custom-select"
                            style="width: 240px"
                        ></SelectPage>
                    </el-form-item>
                    <el-form-item label="采购类型" props="is_1688">
                        <el-select v-model="queryParams.is_1688" placeholder="全部" clearable size="small" style="width: 240px">
                            <el-option v-for="(dict, index) in dict.statusList" :key="index" :label="dict.label" :value="dict.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="创建时间" prop="create_time">
                        <el-date-picker v-model="queryParams.create_time" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 240px">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label=" ">
                        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>

            <div class="card">
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd">生成采购单</el-button>
                    </el-col>
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>
                <!-- class="table-wrap" -->
                <div >
                    <el-table
                        v-loading="loading"
                        :data="tableData"
                        row-key="supply_name"
                        border
                        script
                        :span-method="arraySpanMethod"
                        default-expand-all
                        class="expend-table summary-table"
                    >
                    <!-- show-summary
                        :summary-method="getSummaries" -->
                        <el-table-column label="全选" type="expand" width="50">
                            <template #header>
                                <el-checkbox v-model="checkAll" :indeterminate="indeterminate" @change="handleCheckAllChange"></el-checkbox>
                            </template>
                            <template slot-scope="scope">
                                <el-table
                                    :data="scope.row.sku_info"
                                    border
                                    :show-header="false"
                                    class="sub-table"
                                    :ref="`sub-table-${scope.$index}`"
                                    @selection-change="val => handleSelectionChange(val, scope.$index)"
                                >
                                    <el-table-column type="selection" width="50"> </el-table-column>
                                    <el-table-column label="商品信息" prop="" min-width="250">
                                        <template slot-scope="subScope">
                                            <div class="flex">
                                                <div style="width: 60px">
                                                    <ImageUploadImg v-model="subScope.row.image_url" :readOnly="true" class="small-img"></ImageUploadImg>
                                                </div>
                                                <div>
                                                    <el-link type="primary">{{ subScope.row.seller_sku }}</el-link>
                                                    <div>{{ subScope.row.spu }}</div>
                                                </div>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="1688商品信息" prop="" min-width="250">
                                        <template slot-scope="subScope">
                                            <div class="flex">
                                                <div style="width: 60px">
                                                    <ImageUploadImg v-model="subScope.row['1688_product_image']" :readOnly="true" class="small-img"></ImageUploadImg>
                                                </div>
                                                <div v-if="subScope.row['1688_product_image']">
                                                    <div>
                                                        <el-link type="primary" @click="toProductPage(subScope.row['1688_product_url'])">{{ subScope.row['1688_product_name'] }}</el-link>
                                                    </div>
                                                    <div> 
                                                        <span v-if="subScope.row.varient_colour">颜色：{{ subScope.row.varient_colour }}</span>
                                                        <span v-if="subScope.row.varient_size">尺码：{{ subScope.row.varient_size }}</span>
                                                    </div>
                                                    <div><el-button type="text" style="padding: 4px 0" @click="showSingleDddDialog(subScope.row)">更换配对</el-button></div>
                                                </div>
                                                <div v-else><el-button type="text" @click="showSingleDddDialog(subScope.row)" :disabled="subScope.row.is_1688 == 2">新增配对</el-button></div>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="采购员" min-width="140" align="center">
                                        <template slot-scope="subScope">
                                            <el-select v-model="subScope.row.operate_id" placeholder="请选择采购者" clearable size="small" style="width: 120px" @change="changeOperate(subScope.row)">
                                                <el-option v-for="(dict, index) in dict.salesmanList" :key="index" :label="dict.username" :value="dict.operater_id" />
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="单价" prop="purchase_price" min-width="100" align="center"></el-table-column>
                                    <el-table-column label="数量" min-width="100" align="center">
                                        <template slot-scope="subScope">
                                            <el-input
                                                v-model="subScope.row.purchase_nums"
                                                placeholder="数量"
                                                size="mini"
                                                style="width: 80px"
                                                @blur="countChange(subScope.row)"
                                            ></el-input>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="小计" min-width="100" align="center">
                                        <template slot-scope="subScope">
                                            <div style="color: #f40">{{ (subScope.row.purchase_nums * subScope.row.purchase_price).toFixed(2) }}</div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="类别" min-width="100" align="center">
                                        <template slot-scope="subScope">
                                            <span>{{ subScope.row.is_1688 | formatLabelByValueFuzzy(dict.statusList) }}</span>
                                        </template>
                                    </el-table-column>
                                    <el-table-column label="操作" width="120">
                                        <template slot-scope="subScope">
                                            <div><el-button type="text" @click="showChangeSupply(subScope.row)">更换供应商</el-button></div>
                                            <div><el-button type="text" @click="deleteRow(subScope.row)">删除</el-button></div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </template>
                        </el-table-column>
                        <el-table-column label="商品信息" prop="order_id" min-width="250">
                            <template #header>
                                <div class="flex column align-center">
                                    <span>商品信息</span>
                                </div>
                            </template>
                            <template slot-scope="scope">
                                <div class="flex">
                                    <el-checkbox
                                        v-model="selectAll[scope.$index]"
                                        :indeterminate="selectHalf[scope.$index]"
                                        @change="val => handleSelectAllChange(val, scope.$index)"
                                        style="margin-right: 8px"
                                    ></el-checkbox>
                                    <span style="position: relative; padding-right: 36px"> 供应商：{{ scope.row.supply_name }} </span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="" prop="" min-width="250"></el-table-column>
                        <el-table-column label="采购员" min-width="140" align="center"></el-table-column>
                        <el-table-column label="单价" min-width="100" align="center"></el-table-column>
                        <el-table-column label="数量" min-width="100" align="center"></el-table-column>
                        <el-table-column label="小计" min-width="100" align="center"></el-table-column>
                        <el-table-column label="类别" min-width="100" align="center"></el-table-column>
                        <el-table-column label="操作" width="120" align="center"></el-table-column>
                    </el-table>
                </div>
                <div class="sums-warp">
                        <span class="sums-item">供货商数量：<span class="text-red">{{ totalSupply }}</span></span>
                        <span class="sums-item">商品种类：<span>{{ totalSku }} 种</span></span>
                        <span class="sums-item">数量总计：<span>{{ totalSums }} 件</span></span>
                        <span class="sums-item">商品金额总计（不含运费）：<span class="text-red">{{ totalAmount }}元</span></span>
                </div>
                <pagination v-show="total > 0" :total="total" :page.sync="pageInfo.page" :limit.sync="pageInfo.limit" @pagination="getList" />
            </div>

            <ChangeSupplyDialog v-model="changeSupplyDialog.visible" v-if="changeSupplyDialog.visible" :params="changeSupplyDialog.data" @success="handleQuery"></ChangeSupplyDialog>
            <RemarkDialog v-model="remarkDialog.visible" :params="remarkDialog.data" @success="handleQuery"></RemarkDialog>
            <singleAddDialog v-model="singleDddDialog.visible" v-if="singleDddDialog.visible" :params="singleDddDialog.data" @success="handleQuery"></singleAddDialog>
        </div>
    </div>
</template>
<script>
import { suggestPlan, getPurchaserList, updatePurchaseQuantity, delPlan, editPlan, editOperater } from '@/api/purchase'
import { parseTime } from '@/utils/quickadmin'
import ChangeSupplyDialog from './components/changeSupplyDialog.vue'
import RemarkDialog from './components/remarkDialog.vue'
import SingleAddDialog from './components/SingleAddDialog.vue'
export default {
    name: 'PurchaseSuggest',
    components: { ChangeSupplyDialog, RemarkDialog, SingleAddDialog },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            tableData: [],
            // 状态数据字典
            dict: {
                salesmanList: [],
                statusList: [
                    { label: '1688下单', value: 1 },
                    { label: '手工下单', value: 2 },
                ]
            },
            pageInfo: {
                page: 1,
                limit: 10,
            },
            // 查询参数
            queryParams: {
                purchase_status: undefined,
                seller_sku: undefined,
                spu: undefined,
                operate_id: undefined,
                supply_id: undefined,
                is_1688: undefined,
                create_time: [],
            },
            syncDialog: {
                visible: false,
                data: {},
            },
            remarkDialog: {
                visible: false,
                data: {},
            },
            changeSupplyDialog: {
                visible: false,
                data: {},
            },
            editModal: {
                id: '',
                purchase_quantity: '',
            },
            editData: {
                visible: false,
                data: {},
            },
            singleDddDialog: {
                visible: false,
                data: {},
            },
            checkAll: false,
            indeterminate: false,
            selectAll: [],
            selectHalf: [],
            selectList: [],
        }
    },
    async created() {
        this.loading = true
        try {
            const salesmanData = await getPurchaserList()
            this.dict.salesmanList = salesmanData?.data ?? []
        } catch (error) {
            this.loading = false
        }
        this.getList()
    },
    mounted() {},
    beforeDestroy() {},
    computed: {
        selectSupInfoList() {
            let list = []
            this.tableData.forEach(item => {
                item.sku_info.forEach(item => {
                    if (this.selectList.includes(item.id)) {
                        list.push(item)
                    }
                })
            })
            return list
        },
        totalSupply() {
            return this.selectAll.filter(item=>item==true).length + this.selectHalf.filter(item=>item==true).length
        },
        totalSku() {
            return this.selectSupInfoList.length
        },
        totalSums() {
            let sum = this.selectSupInfoList.reduce((sum, row) => {
                return (
                    sum + (row.purchase_nums  || 0)
                )
            }, 0)
            return sum        
        },
        totalAmount() {
            let sum = this.selectSupInfoList.reduce((sum, row) => {
                return (
                    sum + (row.purchase_nums * row.purchase_price || 0)
                )
            }, 0)
            return sum.toFixed(2)
        },
    },
    methods: {
        changeOperate(row) {
            editOperater({ id: row.id, operate_id: row.operate_id }).then(res => {
                this.$message.success('修改成功')
                this.getList()
            })
        },
        showSingleDddDialog(row) {
            this.singleDddDialog.visible = true
            this.singleDddDialog.data = row
        },
        handleAdd() {
            if (!this.selectList.length) {
                return this.$message.warning('请选择商品')
            }
            this.$router.push({
                path: '/purchase/order/plan-detail',
                query: { ids: this.selectList },
            })
        },
        countChange(row) {
            editPlan({ id: row.id, planNumber: row.purchase_nums }).then(res => {
                this.$message.success('修改成功')
                this.getList()
            })
        },
        toProductPage(url) {
            window.open(url)
        },
        handleCheckAllChange(val) {
            const selectList = []
            this.tableData.map((item, index) => {
                if (!val) {
                    this.$refs[`sub-table-${index}`].clearSelection()
                } else {
                    item.sku_info.forEach(temp => {
                        this.$refs[`sub-table-${index}`].toggleRowSelection(temp, true)
                        selectList.push(temp.id)
                    })
                }
            })
            this.selectList = val ? selectList : []
            this.indeterminate = false
        },
        handleSelectAllChange(val, index) {
            const skuInfo = this.tableData[index].sku_info
            if (val) {
                skuInfo.forEach(item => {
                    this.$refs[`sub-table-${index}`].toggleRowSelection(item, true)
                })
                this.selectList = Array.from(new Set([...this.selectList, ...skuInfo.map(item => item.id)]))
            } else {
                this.$refs[`sub-table-${index}`].clearSelection()
                this.selectList = this.selectList.filter(item => !skuInfo.map(sku => sku.id).includes(item))
            }
            // 使用 this.$set 确保响应式更新
            this.$set(this.selectAll, index, val)
            this.$set(this.selectHalf, index, false)

            // 更新全局全选和半选状态
            this.updateCheckAllState()
            this.$forceUpdate()
        },
        handleSelectionChange(val, index) {
            const selectedIds = val.map(item => item.id)
            const allIds = this.tableData[index].sku_info.map(item => item.id)

            this.selectList = Array.from(new Set([...this.selectList.filter(id => !allIds.includes(id)), ...selectedIds]))

            // 更新当前子表的全选和半选状态
            this.$set(this.selectAll, index, selectedIds.length === allIds.length)
            this.$set(this.selectHalf, index, selectedIds.length > 0 && selectedIds.length < allIds.length)

            // 更新全局的 checkAll 和 indeterminate 状态
            this.checkAll = this.selectAll.every(item => item)
            this.indeterminate = this.selectAll.some(item => item) && !this.checkAll

            // 更新全局全选和半选状态
            this.updateCheckAllState()
            this.$forceUpdate()
        },
        updateCheckAllState() {
            // 更新全局全选和半选状态
            this.checkAll = this.selectAll.every(item => item)
            this.indeterminate = this.selectAll.some(item => item) && !this.checkAll
        },
        addRemark(row) {
            this.remarkDialog.visible = true
            this.remarkDialog.data = row
        },
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 1) {
                return [1, 10]
            } else if (columnIndex === 0) {
                return [1, 1]
            } else if (columnIndex == 11) {
                return [1, 2]
            } else {
                return [0, 0]
            }
        },
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            const skuList = this.tableData.find(item => item.order_id === row.order_id)?.sku_info
            // 判断是否需要合并单元格的列
            if ([1, 2, 3, 4, 5, 6, 7].includes(columnIndex)) {
                if (rowIndex === 0) {
                    return {
                        rowspan: skuList.length,
                        colspan: 1,
                    }
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0,
                    }
                }
            }
        },

        //列表
        getList() {
            this.loading = true
            const qyparams = {
                ...this.pageInfo,
                ...this.queryParams,
                ids: this.$route.query?.ids ?? null,
            }
            if (qyparams.create_time?.length == 2) {
                qyparams.create_time = [parseTime(qyparams.create_time[0], 'y-m-d'), parseTime(qyparams.create_time[1], 'y-m-d')]
            }
            suggestPlan(qyparams)
                .then(response => {
                    this.tableData = response.data.list
                    this.total = response.data.total

                    // 根据tableData.sku_info的长度，初始化edit
                    this.tableData.map(temp => {
                        this.selectAll.push(false) // 默认未全选
                        this.selectHalf.push(false) // 默认未半选
                        temp.sku_info.forEach(item => {
                            item.edit = false
                            return { ...item }
                        })
                    })
                    this.$nextTick(()=>{
                        this.showSummariesPosition()
                    })
                })
                .finally(() => {
                    this.loading = false
                })
        },

        // 搜索按钮操作
        handleQuery() {
            this.pageInfo.page = 1
            this.getList()
        },

        // 重置按钮操作
        resetQuery() {
            this.resetForm('queryForm')

            this.handleQuery()
        },
        showChangeSupply(row) {
            this.changeSupplyDialog.visible = true
            this.changeSupplyDialog.data = row
        },

        // 删除按钮操作
        deleteRow(row) {
            this.$confirm('是否确认删除?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    await delPlan({ id: row.id })
                    this.getList()
                    this.msgSuccess('操作成功')
                })
                .catch(() => {})
        },
        getSummaries({ columns, data }) {
            const sums = []
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = '总计'
                    return
                }
                if (column.label === 'purchase_price' || column.label === 'purchase_nums') {
                    sums[index] = ''
                    return
                }
                if (column.label === '小计') {
                    const total = data.reduce((sum, row) => {
                        return (
                            sum +
                            row.sku_info.reduce((subSum, sku) => {
                                return subSum + (sku.purchase_nums * sku.purchase_price || 0)
                            }, 0)
                        )
                    }, 0)
                    sums[index] = total.toFixed(2)
                } else {
                    sums[index] = ''
                }
            })
            return sums
        },
        showSummariesPosition() {
            let table = document.querySelector('.summary-table')
            let tdList = table.querySelectorAll('.el-table__footer td')
            if (tdList.length > 0) {
                let html = tdList[tdList.length - 3].querySelector('.cell')
                html.innerHTML = "<span class='summary-row'>" + this.totalAmount + '</span>'
            }
        }
    },
}
</script>
<style>
.summary-row {
    color: #f40;
    font-size: 16px;
    font-weight: bold;
}
</style>
<style scoped>
.ball {
    display: block;
    position: fixed;
    width: 20px; /* 小球的宽度 */
    height: 20px; /* 小球的高度 */
    background-color: #f40; /* 小球的颜色 */
    border-radius: 50%; /* 圆形 */
    z-index: 9999; /* 确保在最上层 */
    pointer-events: none; /* 防止干扰点击事件 */
    opacity: 1; /* 确保初始可见 */
    transition: all 0.6s cubic-bezier(0.49, -0.29, 0.75, 0.41); /* 动画效果 */
}
::v-deep .expend-table .el-table__expanded-cell[class*='cell'] {
    padding: 0 !important;
}
.custom-select .el-select-dropdown__item {
    max-width: 450px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
.border-cell {
    padding: 0 !important;
}
.border-cell .cell {
    padding: 0 !important;
}
.border-cell-item {
    padding: 10px;
    border-bottom: 1px solid #dfe6ec;
}
.border-cell-item:last-child {
    border-bottom: 0;
}
.el-tabs--border-card {
    box-shadow: none;
    border-bottom: 0;
}

::v-deep .el-tabs .el-tabs__content {
    padding: 0;
    border-bottom: 0;
}
.table-wrap {
    padding: 4px 0 0 0;
    border-bottom: 1px solid #dfe4ed;
    border-left: 1px solid #dfe4ed;
    border-right: 1px solid #dfe4ed;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
}

</style>
<style lang="scss" scoped>
.sums-warp {
    padding: 8px 24px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    .sums-item{
        color: #666;
        margin-left: 36px;
    }
}
.text-red {
    color: #f40;
    font-size: 16px;
    font-weight: bold;
}
::v-deep .cart-body {
    .el-checkbox__label {
        width: 0;
        padding: 0;
        color: transparent;
    }
}
.cart-header {
    padding: 8px 12px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
}
.cart-title {
    font-size: 14px;
    padding: 8px 12px;
    background-color: #ddd;
}
.cart-row {
    font-size: 14px;
    padding: 8px 12px;
    border-bottom: 1px solid #f5f5f5;
}
::v-deep .sub-table {
    border: 0;
    &::after {
        background: transparent;
    }
    /* 隐藏子表格的滚动条 */
    .el-table__body-wrapper {
        overflow-x: hidden !important;
    }
}

::v-deep .small-img {
    .upload-img-wrap {
        width: 54px;
    }
    .upload-img-box {
        width: 50px;
        height: 50px;
    }
    .upload-img {
        width: 48px;
        height: 48px;
    }
}
</style>
